# -*- coding: utf-8 -*-
# @Time : 2022/1/4 15:48

import time
from Common.mysql import db
from src.User.Database.user_database import User
from Common.public_method import md_5
from src.User.Database.user_database import UserSchema
from Common.yaml_method import YamlMethod
from src.User.feishu_user_info import LarkUserInfo
from src.User.token import generate_auth_token
from Common.public_method import utc_8


class Login:
    """
    账号密码登录接口
    """

    @staticmethod
    def login(user_name, password):
        """
        登录接口
        :param user_name: 前端传过来的用户名
        :param password: 前端传过来的密码
        :return: 登录结果和用户信息
        """
        # 定义响应体data内容字典格式变量data
        data = {}
        # 定义响应体字典格式变量dic
        dic = {}

        code = YamlMethod().read_data('code.yaml')['code']

        # 查询数据库，校验用户名和密码
        user = User.query.filter_by(userName=user_name).first()
        user_schema = UserSchema()
        user_data = user_schema.dump(user)

        if len(user_data) != 0:
            # 判断账号是否被禁用
            if user_data['status'] != '启用':
                dic['code'] = code[8]
                dic['message'] = '账号被禁用，请联系管理员'
                return dic
            password = md_5(password)
            if user_data['password'] == password:
                dic['code'] = code[0]
                dic['message'] = '登录成功'

                # 生成token
                token_data = {'user_id': user_data['id'], 'user_name': user_data['realName'], 'password': password}
                token = generate_auth_token(token_data)
                data['token'] = token

                # 记录登录时间
                login_time = utc_8()
                user.lastLogin_time = login_time
                db.session.commit()

                # 返回角色和账号状态信息
                data['roles'] = [user_data['roles']]
                data['status'] = user_data['status']
                dic['data'] = data
                return dic
            else:
                dic['code'] = code[2]
                dic['message'] = '用户名或密码错误'
                return dic
        else:
            dic['code'] = code[3]
            dic['message'] = '用户不存在'
            return dic

    @staticmethod
    def feishu_login(pass_code):
        """
        飞书登录逻辑
        :param pass_code: 飞书授权后返回重定向URL中的code参数
        :return:
        """
        # 定义响应体data内容字典格式变量data
        data = {}
        # 定义响应体字典格式变量dic
        dic = {}
        code = YamlMethod().read_data('code.yaml')['code']

        # 用pass_code去获取飞书用户的openID
        user_info = LarkUserInfo().get_user_info(pass_code)
        try:
            open_id = user_info['data']['open_id']
            if not open_id:
                dic['data'] = data
                dic['code'] = code[3]
                dic['message'] = '授权失败，未获取到飞书用户信息'
                return dic
        except Exception as e:
            data['err'] = str(e)
            dic['data'] = data
            dic['code'] = code[3]
            dic['message'] = '授权失败，未获取到飞书用户信息'
            return dic
        user_name = user_info['data']['name']

        # 查询数据库，校验用户名的openID
        user = User.query.filter_by(userName=user_name).first()
        user_schema = UserSchema()
        user_data = user_schema.dump(user)

        if len(user_data) != 0:
            # 判断账号是否被禁用
            if user_data['status'] != '启用':
                dic['code'] = code[8]
                dic['message'] = '账号被禁用，请联系管理员'
                return dic
            # 登录
            dic['code'] = code[0]
            dic['message'] = '登录成功'
            # 生成token
            token_data = {'user_id': user_data['id'], 'user_name': user_data['realName']}
            token = generate_auth_token(token_data)
            data['token'] = token
            # 记录登录时间
            login_time = utc_8()
            user.lastLogin_time = login_time
            db.session.commit()
            # 返回角色和账号状态信息
            data['roles'] = [user_data['roles']]
            data['status'] = user_data['status']
            dic['data'] = data
            return dic
        else:
            # 用户信息入库
            create_time = utc_8()
            # 默认用户新注册的角色为 development
            roles = 'test'
            status = '启用'
            login_time =utc_8()
            # 用户信息插入数据库
            try:
                user = User(openId=open_id, userName=user_name, realName=user_name, roles=roles,
                            create_time=create_time, status=status, lastLogin_time=login_time)
                db.session.add(user)
                db.session.commit()
            except Exception as e:
                data['err'] = str(e)
                dic['data'] = data
                dic['code'] = code[1]
                dic['message'] = '登录失败'
                return dic
            # 查询数据库用户信息
            user = User.query.filter_by(openId=open_id).first()
            user_schema = UserSchema()
            user_data = user_schema.dump(user)
            # 生成token
            token_data = {'user_id': user_data['id'], 'user_name': user_data['realName']}
            token = generate_auth_token(token_data)
            data['token'] = token
            # 返回角色和账号状态信息
            data['roles'] = roles
            data['status'] = status
            dic['data'] = data
            dic['code'] = code[0]
            dic['message'] = '登录成功'
            return dic



